package top.lyc829.zzl_android.ui.index.serach;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.spinner.materialspinner.MaterialSpinner;

import java.io.IOException;
import java.util.List;

import okhttp3.Response;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivitySearchDetialBinding;
import top.lyc829.zzl_android.logic.bean.BaseBean;
import top.lyc829.zzl_android.logic.bean.DynamicBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.SearchData;
import top.lyc829.zzl_android.logic.bean.ShareBean;
import top.lyc829.zzl_android.logic.bean.TeamSimpleBean;
import top.lyc829.zzl_android.logic.bean.TravelsSimpleBean;
import top.lyc829.zzl_android.logic.bean.UserInfoBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.DynamicType;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.ReplayType;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.base_detail.BaseDetailActivity;
import top.lyc829.zzl_android.ui.custom_view.ShareMsgDialog;
import top.lyc829.zzl_android.ui.index.RecyclerViewAdapter;
import top.lyc829.zzl_android.ui.profile.follow.user.FollowUserAdapter;
import top.lyc829.zzl_android.ui.profile.follow.user_detail.OtherUserDetailActivity;
import top.lyc829.zzl_android.ui.profile.user_dtc.dynamic.UserDynamicAdapter;
import top.lyc829.zzl_android.ui.team.TeamRecyclerAdapter;
import top.lyc829.zzl_android.ui.team.team_detail.TeamDetailActivity;
import top.lyc829.zzl_android.ui.thing.dynamic.DynamicRecyclerViewAdapter1;
import top.lyc829.zzl_android.ui.thing.dynamic_detail.DynamicDetailActivity;
import top.lyc829.zzl_android.ui.thing.travel_detail.TravelDetailActivity;
import top.lyc829.zzl_android.ui.thing.travels.TravelsAdapter;

public class SearchDetial extends AppCompatActivity {

    ActivitySearchDetialBinding binding;

    SearchData searchData;
    SearchData newSearchData;
    SearchDetialViewModel mViewModel;

    RecyclerViewAdapter adapterBase;
    TravelsAdapter adapterTravel;
    TeamRecyclerAdapter adapterTeam;
    DynamicRecyclerViewAdapter1 adapterDynamic;
    FollowUserAdapter adapterUser;

    GridLayoutManager layoutManager;
    LinearLayoutManager linearLayoutManager;

    ShareMsgDialog shareMsgDialog;
    MiniLoadingDialog mMiniLoadingDialog;


    PageInfo pageInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySearchDetialBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        newSearchData = new SearchData();
        pageInfo = new PageInfo();

        mViewModel = new ViewModelProvider(this).get(SearchDetialViewModel.class);
        searchData = (SearchData) getIntent().getSerializableExtra("searchData");

 //       binding.editText.setText(searchData.getString());
        ((TitleBar) findViewById(R.id.m_title_bar_searchDetial)).setLeftClickListener(v -> {
            finish();
        });

        mMiniLoadingDialog =  WidgetUtils.getMiniLoadingDialog(this);
        mMiniLoadingDialog.updateMessage("加载中");
        mMiniLoadingDialog.setCancelable(false);

//
//        binding.addSearchType.setOnItemSelectedListener((view, position, id, item) -> newSearchData.setType(position));
//
//        binding.imageButton.setOnClickListener(v -> {
//            searchData.setType(newSearchData.getType());
//            searchData.setString(binding.editText.getText().toString());
//            pageInfo.reset();
//            mViewModel.getSearchDetailLiveDataServer(newSearchData.getType(), binding.editText.getText().toString(), 1, Utils.getUserId());
//        });


        initRecycler();

        adapterUser.setOnItemClickListener((adapter, view, position) -> {

            Intent intent = new Intent(SearchDetial.this, OtherUserDetailActivity.class);
            intent.putExtra("id", adapterUser.getItem(position).getId());
            startActivity(intent);
        });


        adapterDynamic.setOnItemClickListener((itemView, item, position) -> {
            Intent intent = new Intent(SearchDetial.this, DynamicDetailActivity.class);
            intent.putExtra("id", adapterDynamic.getItem(position).getDynamicId());
            startActivity(intent);
        });
        adapterDynamic.setOnItemChildClickListener((holder, view, position) -> {
            if (view.getId() == R.id.dynamic_praise) {
                if (!Utils.isLogin()) {
                    Utils.showToast("请先登录");
                    return;
                }
                if (mViewModel.getDynamicLiveData().getValue() != null) {
                    final DynamicBean dynamicBean = adapterDynamic.getItem(position);
                    View itemView = binding.searchDetailRecycler.getLayoutManager().findViewByPosition(position);
                    // 点击后设置不可点击
                    itemView.findViewById(R.id.dynamic_praise).setClickable(false);
                    if (dynamicBean.getIsLike().equals(0)) {
                        sendLike(Utils.getUserId(), dynamicBean.getDynamicId(), position);
                    } else {
                        sendUnLike(Utils.getUserId(), dynamicBean.getDynamicId(), position);
                    }
                }

            } else if (view.getId() == R.id.dynamic_share) {
                shareToDynamic(position);
            } else if (view.getId() == R.id.dynamic_comment) {
                Intent intent = new Intent(SearchDetial.this, DynamicDetailActivity.class);
                intent.putExtra("id", adapterDynamic.getData().get(position).getDynamicId());
                intent.putExtra("position", position);
                intent.putExtra("is_comment", true);
                startActivity(intent);
            } else if (view.getId() == R.id.edit_share) {
                goOriginDynamic(position);
            } else if (view.getId() == R.id.my_dynamic_user_Url) {
                Intent intent = new Intent(SearchDetial.this, OtherUserDetailActivity.class);
                intent.putExtra("id", adapterDynamic.getItem(position).getUserId());
                startActivity(intent);
            }
        });

        adapterTeam.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(SearchDetial.this, TeamDetailActivity.class);
            intent.putExtra("team_id", adapterTeam.getItem(position).getId());
            startActivity(intent);
        });

        adapterTravel.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(SearchDetial.this, TravelDetailActivity.class);
            intent.putExtra("travel_id", adapterTravel.getItem(position).getId());
            startActivity(intent);
        });

        adapterBase.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(SearchDetial.this, BaseDetailActivity.class);
            intent.putExtra("id", adapterBase.getItem(position).getId());
            startActivity(intent);
        });

        binding.refreshLayout.autoRefresh();

        binding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                request();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageInfo.reset();
                request();
            }
        });
        //mViewModel.getSearchDetialLiveDataServer(searchData.getType(), searchData.getString(), 1);

        observer();

    }

    private void shareToDynamic(int position) {
        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
            return;
        }

        shareMsgDialog = null;
        DynamicBean dynamic = adapterDynamic.getItem(position);
        shareMsgDialog = new ShareMsgDialog(
                this,
                R.style.dialog_center,
                new ShareBean(dynamic.getUserName(), dynamic.getDynamicText() ,dynamic.getDynamicUrl().get(0)));
        shareMsgDialog.setmOnTextSendListener(msg -> {
            shareMsgDialog.dismiss();
            mMiniLoadingDialog.show();

            Network.shareToDynamic(DynamicType.DYNAMIC, dynamic.getDynamicId(), Utils.getUserId(), msg, new HttpUtil.MyCallback() {
                @Override
                public void success(Response res) throws IOException {
                    String resStr = res.body().string();
                    ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                    if (resultBean.getCode().equals(200)) {
                        runOnUiThread(() ->{
                            mMiniLoadingDialog.dismiss();
                            Utils.showToast("分享成功");
                        });
                    } else {
                        failed(new IOException(resultBean.getMsg()));
                    }
                }

                @Override
                public void failed(IOException e) {
                    runOnUiThread(() -> {
                        Utils.Sout(e.getMessage());
                        mMiniLoadingDialog.dismiss();
                    });

                }
            });

        });

        shareMsgDialog.show();
    }

    private void sendLike(int userId, Integer dynamicId, int position) {
        Network.sendLike(userId, ReplayType.DYNAMIC, dynamicId, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resStr = res.body().string();
                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                if (resultBean.getCode().equals(200)) {
                    runOnUiThread(() -> {
                        View itemView = binding.searchDetailRecycler.getLayoutManager().findViewByPosition(position);
                        // 点击后设置不可点击
                        itemView.findViewById(R.id.dynamic_praise).setClickable(true);
                        adapterDynamic.getItem(position).setIsLike(1);
                        adapterDynamic.getItem(position).setLikes(adapterDynamic.getItem(position).getLikes() + 1);
                        adapterDynamic.notifyDataSetChanged();
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                runOnUiThread(() -> {
                    Utils.SoutErr(e.getMessage());
                    View itemView = binding.searchDetailRecycler.getLayoutManager().findViewByPosition(position);
                    // 点击后设置不可点击
                    if (itemView.findViewById(R.id.dynamic_praise) != null) {
                        itemView.findViewById(R.id.dynamic_praise).setClickable(true);
                    }
                });

            }
        });
    }

    private void sendUnLike(int userId, Integer dynamicId, int position) {
        Network.sendUnLike(userId, ReplayType.DYNAMIC, dynamicId, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resStr = res.body().string();
                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                if (resultBean.getCode().equals(200)) {
                    runOnUiThread(() -> {
                        View itemView = binding.searchDetailRecycler.getLayoutManager().findViewByPosition(position);
                        // 点击后设置不可点击
                        itemView.findViewById(R.id.dynamic_praise).setClickable(true);
                        adapterDynamic.getItem(position).setIsLike(0);
                        adapterDynamic.getItem(position).setLikes(adapterDynamic.getItem(position).getLikes() - 1);
                        adapterDynamic.notifyDataSetChanged();
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                runOnUiThread(() -> {
                    Utils.SoutErr(e.getMessage());
                    View itemView = binding.searchDetailRecycler.getLayoutManager().findViewByPosition(position);
                    // 点击后设置不可点击
                    if (itemView.findViewById(R.id.dynamic_praise) != null) {
                        itemView.findViewById(R.id.dynamic_praise).setClickable(true);
                    }
                });
            }
        });
    }

    // 去原始动态
    private void goOriginDynamic(int position) {
        DynamicBean item = adapterDynamic.getItem(position);
        Intent intent = null;
        if (item.getType().equals(DynamicType.BASE)) {
            intent  = new Intent(SearchDetial.this, BaseDetailActivity.class);
            intent.putExtra("id", item.getTypeId());
        } else if (item.getType().equals(DynamicType.DYNAMIC)) {
            intent  = new Intent(SearchDetial.this, DynamicDetailActivity.class);
            intent.putExtra("id", item.getTypeId());
        }else if (item.getType().equals(DynamicType.TRAVEL)) {
            intent  = new Intent(SearchDetial.this, TravelDetailActivity.class);
            intent.putExtra("travel_id", item.getTypeId());
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    private void initRecycler() {

        adapterBase = adapterBase == null ? new RecyclerViewAdapter() : adapterBase;
        adapterTeam = adapterTeam == null ? new TeamRecyclerAdapter() : adapterTeam;
        adapterTravel = adapterTravel == null ? new TravelsAdapter() : adapterTravel;
        adapterDynamic = adapterDynamic == null ? new DynamicRecyclerViewAdapter1() : adapterDynamic;
        adapterUser = adapterUser == null ? new FollowUserAdapter() : adapterUser;


        if (searchData.getType().equals(0)) {
            if (layoutManager == null) {
                layoutManager = new GridLayoutManager(this, 2);
            }
            binding.searchDetailRecycler.setLayoutManager(layoutManager);
            //baseAdapter = new BaseAdapter(null);
            adapterBase.setAnimationEnable(true);   // recyclerview加载动画
            binding.searchDetailRecycler.setAdapter(adapterBase);
        } else if (searchData.getType().equals(1)) {
            if (linearLayoutManager == null) {
                linearLayoutManager = new LinearLayoutManager(this);
            }
            binding.searchDetailRecycler.setLayoutManager(linearLayoutManager);
            binding.searchDetailRecycler.setAdapter(adapterTravel);
        } else if (searchData.getType().equals(2)) {
            if (linearLayoutManager == null) {
                linearLayoutManager = new LinearLayoutManager(this);
            }
            binding.searchDetailRecycler.setLayoutManager(linearLayoutManager);
            binding.searchDetailRecycler.setAdapter(adapterTeam);
        } else if (searchData.getType().equals(3)) {
            if (linearLayoutManager == null) {
                linearLayoutManager = new LinearLayoutManager(this);
            }
            binding.searchDetailRecycler.setLayoutManager(linearLayoutManager);
            binding.searchDetailRecycler.setAdapter(adapterDynamic);
        } else if (searchData.getType().equals(4)) {
            if (linearLayoutManager == null) {
                linearLayoutManager = new LinearLayoutManager(this);
            }
            binding.searchDetailRecycler.setLayoutManager(linearLayoutManager);
            binding.searchDetailRecycler.setAdapter(adapterUser);
        }

    }

    private void observer() {
        mViewModel.getBaseLiveData().observe(this, baseBeans -> {
            if (pageInfo.isFirstPage()) {
                adapterBase.setList(baseBeans);
                binding.refreshLayout.finishRefresh();
            } else {
                adapterBase.addData(baseBeans);
                binding.refreshLayout.finishLoadMore();
            }
            if (baseBeans==null||baseBeans.size() < PageInfo.MAX_ITEM)
                binding.refreshLayout.finishLoadMoreWithNoMoreData();
            else {
                binding.refreshLayout.finishLoadMore();
                pageInfo.nextPage();
            }

            if(baseBeans==null||baseBeans.size()==0)
            {
                Utils.showToast("没有更多内容了");
            }
        });

        mViewModel.getDynamicLiveData().observe(this, baseBeans -> {
            initRecycler();
            if (pageInfo.isFirstPage()) {
                adapterDynamic.refresh(baseBeans);
                binding.refreshLayout.finishRefresh();
            } else {
                adapterDynamic.loadMore(baseBeans);
                binding.refreshLayout.finishLoadMore();
            }
            if (baseBeans==null||baseBeans.size() < PageInfo.MAX_ITEM)
                binding.refreshLayout.finishLoadMoreWithNoMoreData();
            else {
                binding.refreshLayout.finishLoadMore();
                pageInfo.nextPage();
            }

            if(baseBeans==null||baseBeans.size()==0)
            {
                Utils.showToast("没有更多内容了");
            }
        });

        mViewModel.getTeamLiveData().observe(this, baseBeans -> {
            initRecycler();
            if (pageInfo.isFirstPage()) {
                adapterTeam.setList(baseBeans);
                binding.refreshLayout.finishRefresh();
            } else {
                adapterTeam.addData(baseBeans);
                binding.refreshLayout.finishLoadMore();
            }
            if (baseBeans==null||baseBeans.size() < PageInfo.MAX_ITEM)
                binding.refreshLayout.finishLoadMoreWithNoMoreData();
            else {
                binding.refreshLayout.finishLoadMore();
                pageInfo.nextPage();
            }

            if(baseBeans==null||baseBeans.size()==0)
            {
                Utils.showToast("没有更多内容了");
            }
        });

        mViewModel.getTravelLiveData().observe(this, baseBeans -> {
            initRecycler();
            if (pageInfo.isFirstPage()) {
                adapterTravel.setList(baseBeans);
                binding.refreshLayout.finishRefresh();
            } else {
                adapterTravel.addData(baseBeans);
                binding.refreshLayout.finishLoadMore();
            }
            if (baseBeans==null||baseBeans.size() < PageInfo.MAX_ITEM)
                binding.refreshLayout.finishLoadMoreWithNoMoreData();
            else {
                binding.refreshLayout.finishLoadMore();
                pageInfo.nextPage();
            }

            if(baseBeans==null||baseBeans.size()==0)
            {
                Utils.showToast("没有更多内容了");
            }
        });

        mViewModel.getUserLiveData().observe(this, baseBeans -> {

            baseBeans.forEach(userInfoBean -> {
                userInfoBean.setIsLike("-1");
            });

            initRecycler();
            if (pageInfo.isFirstPage()) {
                adapterUser.setList(baseBeans);
                binding.refreshLayout.finishRefresh();
            } else {
                adapterUser.addData(baseBeans);
                binding.refreshLayout.finishLoadMore();
            }
            if (baseBeans==null||baseBeans.size() < PageInfo.MAX_ITEM)
                binding.refreshLayout.finishLoadMoreWithNoMoreData();
            else {
                binding.refreshLayout.finishLoadMore();
                pageInfo.nextPage();
            }

            if(baseBeans==null||baseBeans.size()==0)
            {
                Utils.showToast("没有更多内容了");
            }
        });
    }

    private void request() {
        try {
            mViewModel.getSearchDetailLiveDataServer(searchData.getType(), searchData.getString(), pageInfo.getPage(), Utils.getUserId());
        } catch (Exception e) {
            Utils.Sout(e.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        mMiniLoadingDialog.recycle();
        super.onDestroy();
    }
}